package com.helloworld.demo.atomic;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class CASTest {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Entity entity = new Entity();

        //直接报错
        //Unsafe unsafe = Unsafe.getUnsafe();
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        Unsafe unsafe = (Unsafe) field.get(null);

        Field x = Entity.class.getDeclaredField("x");
        long offset = unsafe.objectFieldOffset(x);

        boolean successful;

        successful = unsafe.compareAndSwapInt(entity, offset, 0, 3);
        System.out.println(successful + "\t" + entity.x);

        successful = unsafe.compareAndSwapInt(entity, offset, 3, 5);
        System.out.println(successful + "\t" + entity.x);

        successful = unsafe.compareAndSwapInt(entity, offset, 3, 8);
        System.out.println(successful + "\t" + entity.x);

    }

}

class Entity{
    int x;
}


class CASLock{
    private volatile int state;

    private static Unsafe UNSAFE;

    private static long OFFSET;

    static {
        Field field = null;
        try {
            field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);

            Field x = CASLock.class.getDeclaredField("state");
            OFFSET = UNSAFE.objectFieldOffset(x);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean cas(){
        return UNSAFE.compareAndSwapInt(this,OFFSET,0,1);
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

}
